package com.lxf.cn.redis;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;


/**
 * Created by liaoxuefeng on 2018/11/6.
 */
@Configuration
public class RedisConfiguration {

    @Value("${spring.redis.host}")
    private String host ;

    @Value("${spring.redis.port}")
    private int port ;

    @Value("${spring.redis.database}")
    private int database ;

    @Value("${spring.redis.password}")
    private String password ;

    @Value("${spring.redis.timeout}")
    private int timeout ;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private Integer maxIdle ;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private Long maxWait ;

    @Value("${redis.pool.testOnBorrow}")
    private Boolean testOnBorrow ;

    @Value("${redis.pool.testOnReturn}")
    private Boolean testOnReturn ;

    @Value("${spring.redis.jedis.pool.max-active}")
    private Integer maxActive ;

    private  JedisPool jedisPool;

    @PostConstruct
    public void init(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWait);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setMaxTotal(maxActive);
        jedisPool = new JedisPool(config, host, port, timeout,password,database);
    }


    /**
     * 获取Jedis客户端
     * @return
     */
    public Jedis getJedis() {
        Jedis jedis = null;
        if(null != jedisPool) {
            jedis = jedisPool.getResource();
        }
        return jedis;
    }

    /**
     * 返还资源
     */
    public void returnResource(Jedis jedis) {
        jedis.close();
    }


}
